#include "servicemanager.h"



ServiceManager::ServiceManager()
{
	sp_thread_mutex_init(&mMutex,NULL);
}
ServiceManager::~ServiceManager()
{
	sp_thread_mutex_destroy(&mMutex);
}
void ServiceManager::regService(vector<const std::string>& vecService,SP_Sid_t sid)
{
	sp_thread_mutex_lock( &mMutex );
	for(int i=0;i<vecService.size();i++)
	{
		string classname=vecService.at(i);
		UserList* list=mMapService[classname];
		if(list==NULL)
		{
			list=new UserList();
			mMapService[classname]=list;
		}
		list->add(sid);
	}
	sp_thread_mutex_unlock( &mMutex );
}

void ServiceManager::unregService(std::set<std::string>& setService,SP_Sid_t sid)
{
	sp_thread_mutex_lock( &mMutex );
	set<string>::iterator it=setService.begin();
	while(it!=setService.end())
	{
		string classname=*it;
		UserList* list=mMapService[classname];
		if(list==NULL) {
			it++;
			continue;
		}
		list->remove(sid);
		if(list->getCount()==0)
		{
			delete list;
			mMapService.erase(classname);
		}
		it++;
	}
	sp_thread_mutex_unlock( &mMutex );
}

void ServiceManager::subscribe(vector<const string>& vecService,SP_Sid_t sid)
{
	sp_thread_mutex_lock( &mMutex );
	for(int i=0;i<vecService.size();i++)
	{
		string classname=vecService.at(i);
		UserList* list=mMapSubscriber[classname];
		if(list==NULL)
		{
			list=new UserList();
			mMapSubscriber[classname]=list;
		}
		list->add(sid);
	}
	sp_thread_mutex_unlock( &mMutex );
}

void ServiceManager::unSubscribe(set<string>& setService,SP_Sid_t sid)
{
	sp_thread_mutex_lock( &mMutex );
	set<string>::iterator it=setService.begin();
	while(it!=setService.end())
	{
		string classname=*it;
		UserList* list=mMapSubscriber[classname];
		if(list==NULL) {
			it++;
			continue;
		}
		list->remove(sid);
		if(list->getCount()==0)
		{
			delete list;
			mMapSubscriber.erase(classname);
		}
		it++;
	}
	sp_thread_mutex_unlock( &mMutex );
}